<template>
    <van-nav-bar title="购物车" />
    <div>
        <!-- 单个商品框 -->
        <van-swipe-cell v-for="item in cartList" :key="item.id">
            <!-- 商品内容 -->
            <van-card :price="item.price" :title="item.name" class="goods-card">
                <template #thumb>
                    <div class="left-thumb">
                        
                            <van-checkbox :name="item.name" v-model="item.state" @click="onChecked "/>

                        <van-image :src="item.url"  type="contain" width="70%" />
                    </div>
                </template>

                <template #footer>
                    <div>
                        <van-stepper v-model="item.num" @click="upper"/>
                    </div>
                </template>
                
            </van-card>
            <!-- 右滑删除按钮 -->
            <template #right>
                    <van-button square text="删除" type="danger" class="delete-button" @click="deleteProduct"/>
            </template>
        </van-swipe-cell> 

    </div>
    <!-- 提交订单 -->
        <van-submit-bar  button-text="提交订单" class="box"  @submit="onSubmit" > 
            <van-checkbox v-model="checkeds"  @click="chckedAll">全选</van-checkbox>
            <div class="totals">合计￥:{{total}}</div>
	    </van-submit-bar>

</template>


<script setup lang="ts">
import { useCart } from '@/hooks/cart'
import {ref} from 'vue'
import { useRouter } from 'vue-router'
const { cartList, deleteProduct,onSubmit} = useCart()
const list = cartList.value
const checkeds = ref(false)
const total = ref(0)
const router = useRouter()
// 总价

// 全选
const chckedAll = ()=>{
    for(var i=0;i<list.length;i++){
        if(checkeds.value == true){
            list[i].state = true
        }if(checkeds.value == false){
            list[i].state = false
        }
    }
    total.value = Number(list.reduce((previous, current) => (previous = previous + (current.state ? current.price * current.num : 0)),0))
}
// 单选
const onChecked =()=>{
    checkeds.value = list.every(item=>item.state == true)
    total.value = Number(list.reduce((previous, current) => (previous = previous + (current.state ? current.price * current.num : 0)),0))
}
const upper = ()=>{
    total.value = Number(list.reduce((previous, current) => (previous = previous + (current.state ? current.price * current.num : 0)),0))
} 




</script>

<style scoped lang="scss">

.goods-card{
    margin: 0; 
}

// 右侧滑动删除按钮
.delete-button{
    height: 100%;
}
// 单个商品框
.left-thumb{
    width: 100px;
    height: 60px;
    margin-top: 20px;
    margin-top: 20px;
    display: flex;
}
.totals{
    width: 100px;
    margin-left: 40px;
    margin-right: 20px;
}

.box{
    width: 100%;
    height: 50px;
    position: fixed;
    bottom: 50px;
}

</style>